# -*- coding: utf-8 -*-

import gtk
from kiwi.ui.delegates import GladeDelegate
from kiwi.ui.gadgets import quit_if_last
from kiwi.ui.dialogs import info,yesno
from kiwi.ui.dialogs import warning

from otica.db import connect
from otica.db.connect import transaction
import copy


class BaseEditor(GladeDelegate):
    def __init__(self,excluir, classModel, orderBy, classEditor, widgets):
        GladeDelegate.__init__(self,
                          gladefile="baseeditor",
                          delete_handler=self.delete_handler)
        self.classModel = classModel
        self.orderBy = orderBy
        self.usuarioExlui = excluir
        self.widgets = widgets
        self.salvar_action.set_sensitive(False)
        self.desfazer_action.set_sensitive(False)
        self.baseeditor.set_modal(True)
        self.baseeditor.move(200,250)
        self.baseeditor.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
        if not self.usuarioExlui:
            self.excluir_action.set_visible(False)
        self.connect = connect.get_conection()
        self.isNew = False
         
        self.listModels = ListModel(self.connect, self.classModel, self.orderBy)        
        self.trans = None
        self.tempModel = None
        self.model = self.listModels.getFristModel()
        if not self.model:
            self.editar_action.set_sensitive(False)
        
        self.editor = classEditor()
        self.attach_slave("editor", self.editor)
        self.configura_editor()
        self.set_editable_widgets(False)
        self.proxy = self.editor.add_proxy(self.model, widgets=self.get_widgets())

        self.register_validate_function(self.validity)
        # XXX: Get rid of this
        self.force_validation()
        

    def validity(self, data):
        if self.tempModel:
            self.salvar_action.set_sensitive(self.editor._valid)    
        
    def set_new_transaction(self):
        if not self.trans:
            self.trans = connect.transaction()
            
    def delete_handler(self, *args):
        self.toplevel.destroy()
        
    def configura_editor(self):
        pass

    def get_widgets(self):
        widgets=None
        if self.model:
            widgets=self.widgets
        return widgets        
    
    def on_editar_action__activate(self, action):
        
        self.set_new_transaction()
        self.tempModel = copy.copy(self.model)
        self.isNew = False
        self.baseeditor.set_deletable(False)
        self.salvar_action.set_sensitive(True)
        self.desfazer_action.set_sensitive(True)
        self.novo_action.set_sensitive(False)
        self.primeiro_action.set_sensitive(False)
        self.ultimo_action.set_sensitive(False)
        self.localizar_action.set_sensitive(False)
        self.avancar_action.set_sensitive(False)
        self.voltar_action.set_sensitive(False)
        self.editar_action.set_sensitive(False)
        self.excluir_action.set_sensitive(False)
        self.fechar_action.set_sensitive(False)
        self.set_editable_widgets(True)
        
    
    def desfazer(self):
        self.baseeditor.set_deletable(True)
        self.salvar_action.set_sensitive(False)
        self.desfazer_action.set_sensitive(False)
        self.novo_action.set_sensitive(True)
        self.primeiro_action.set_sensitive(True)
        self.ultimo_action.set_sensitive(True)
        self.localizar_action.set_sensitive(True)
        self.avancar_action.set_sensitive(True)
        self.voltar_action.set_sensitive(True)
        self.editar_action.set_sensitive(True)
        self.excluir_action.set_sensitive(True)
        self.fechar_action.set_sensitive(True)
        self.isNew = False
    
    def on_desfazer_action__activate(self, action):
        
        self.trans.rollback()
        
        if self.tempModel or self.listModels.tamanho == 0:
            self.model = self.tempModel
            self.tempModel = None
        self.trans.begin()
        self.desfazer()

        if self.model:
            self.proxy.set_model(self.model)            
        self.set_editable_widgets(False)
        
        

    def on_novo_action__activate(self, action):
        
        BaseEditor.on_editar_action__activate(self, action)
        self.isNew = True
        self.baseeditor.set_deletable(False)
        self.set_new_transaction()
        self.model = self.classModel.novo(self.trans)
        if self.tempModel == None:
            self.proxy = self.editor.add_proxy(self.model, widgets=self.widgets)
        else:
            self.proxy.set_model(self.model)
        self.set_editable_widgets(True)
        
             
        
    def on_salvar_action__activate(self, action):

        not_valida = self.model.validar(self.trans, self.isNew)
        if not_valida:
            warning(not_valida[1],parent=self.baseeditor)
        else:
            self.trans.commit()
            if self.isNew:
                self.model = self.listModels.set_list_pos(self.model.id)
            self.proxy.set_model(self.model)
            self.set_editable_widgets(False)
            self.desfazer()

    def localizarFunc(self, opt):
        
        self.baseeditor.set_modal(opt)
        tl = self.get_toplevel()
        tl.set_sensitive(opt)
        self.baseeditor.set_deletable(opt)
        self.fechar_action.set_sensitive(opt)
        self.novo_action.set_sensitive(opt)
        self.editar_action.set_sensitive(opt)
        self.localizar_action.set_sensitive(opt)
        
    def on_localizar_action__activate(self, action):

        self.localizarFunc(False)
        
        
    def on_avancar_action__activate(self, action):
        
        model = self.listModels.get_next()
        if model:
            self.model = model
        else:
            info('Último registro foi atingido',parent=self.baseeditor)
        self.proxy.set_model(self.model)
             

    def on_voltar_action__activate(self, action):
        
        model = self.listModels.get_previews()
        if model:
            self.model = model
        else:
            info('Primeiro registro foi atingido',parent=self.baseeditor)
        self.proxy.set_model(self.model)

    
    def on_primeiro_action__activate(self, action):
        
        model = self.listModels.get_frist()
        if model:
            self.model = model
        else:
            info('Primeiro registro foi atingido',parent=self.baseeditor)
        self.proxy.set_model(self.model)
        
    def on_ultimo_action__activate(self, action):
        
        model = self.listModels.get_last()
        if model:
            self.model = model
        else:
            info('Último registro foi atingido',parent=self.baseeditor)
        self.proxy.set_model(self.model)


    def on_excluir_action__activate(self, action):

        if yesno('Tem certeza que deseja exculir o registro?',parent=self.baseeditor) == -8:
            self.set_new_transaction()
            if self.listModels.tamanho > 0:
                self.classModel.delete(self.model.id, connection=self.connect)
                self.trans.commit()
                self.set_new_transaction()
                self.model = self.listModels.gotoPreviews()

        if self.model:
            self.proxy.set_model(self.model)
                
            
    def on_fechar_action__activate(self, action):
        self.delete_handler()


class ListModel:
    
    def __init__(self,connect,classModel,orderBy):
        
        self.connect = connect
        self.classModel = classModel
        self.orderBy = orderBy
        self.models = None
        self.index = 0
        self.tamanho = 0
        self.start_models()
        
    def start_models(self):
        
        self.models = self.classModel.select(connection=self.connect, orderBy=self.orderBy)
        self.tamanho = self.models.count()
        
    def getFristModel(self):
        if self.tamanho > 0:
            return self.models[0]
    
    def set_list_pos(self,id):
        if self.tamanho > 0:
            self.start_models()
            index = 0
            for model in self.models:
                if model.id == id:
                    break
                index+=1
            self.index = index
            return model
    
    def get_next(self):
        if self.tamanho > 0:
            self.index+=1
            try:
                return self.models[self.index]
            except IndexError:
                self.index-=1
                return None
    
    def get_previews(self):
        
        if self.tamanho > 0:
            self.index-=1
            if self.index == -1:
                self.index = 0
                return None
            return self.models[self.index]

    def get_frist(self):
        
        if self.tamanho > 0:
            if self.index == 0:
                return None
            self.index = 0
            return self.models[self.index]

    def get_last(self):
        
        if self.tamanho > 0:
            if self.index == self.tamanho-1:
                return None
            self.index = self.tamanho-1
            return self.models[self.index]
    
    def gotoPreviews(self):
        
        self.start_models()
        if self.tamanho > 0:
            if self.index == 0:
                return self.models[self.index]
            else:
                self.index-=1
                return self.models[self.index] 
                